import React from 'react';
import './ServiceBox.css';
import { Input, Button, Modal} from 'antd';

const { TextArea } = Input;

class ServiceBox extends React.Component {
    constructor(props){
        super(props);
        this.state={
            position:{
                downX:0,   //鼠标按下时客服窗口X坐标
                downY:0,   //鼠标按下时客服窗口的Y坐标
                mouseX:0,   //鼠标点击时的X坐标
                mouseY:0,   //鼠标点击时的Y坐标
                diffX:0,   //鼠标点击位置与父窗口的偏移值
                diffY:0,   //鼠标点击位置与父窗口的偏移值
            },
            moveTo:{    //客服框的移动
                left:600,
                top:100,
            },
            modalVisible:false,    //提示框的显示状态
            chatData:[     //客服聊天数据
                {time:'',name:'客服',chat:'您好，我是铱云智能客服小易！很高兴为您服务！请问您要咨询什么问题？'},
            ],
            ziXun:'',    //咨询的内容
        }
    }
    //获取当前时间
    getNowTime=()=>{
        let time = new Date();
        return time.toLocaleString('chinese', { hour12: false });
    };
    //改变state的值
    changeState=(name,value)=>{
        this.setState({
            [name]:value
        })
    };
    //获取鼠标各项位置
    getPosition(e){
        // e.persist();
        const headerDom=e.target;  //获取header窗口节点
        //鼠标按下时header窗口坐标
        const downX=headerDom.getBoundingClientRect().left;
        const downY=headerDom.getBoundingClientRect().top;
        // 由于Y轴出现滚动条，需要与鼠标保持一致，存储页面相对位置
        // const downY = document.getElementsByClassName('serviceBox')[0].offsetTop;
        //鼠标点击的坐标(页面)
        const mouseX=e.clientX;
        const mouseY=e.clientY;
        //鼠标点击位置与父窗口的位移
        const diffX=mouseX-downX;
        const diffY=mouseY-downY;
        return {downX,downY,mouseX,mouseY,diffX,diffY}
    };
    //鼠标按下事件
    toMove=(e)=>{
        const position=this.getPosition(e);
        this.changeState('position',position);     //保存鼠标位置
        this.props.changeMoveState(true);     //改为 可 移动状态
        window.onmouseover=this.onMouseUp;
        e.target.onmousemove=this.onMouseMove(e);
    };
    // 松开鼠标，设置modal状态为不可移动
    onMouseUp=(e)=>{
        this.props.changeMoveState(false);     //改为 不可 移动状态
    };
    // 鼠标移动重新设置modal的位置
    onMouseMove=(e)=>{
        const position = this.getPosition(e); // 获取鼠标位置数据
        if (this.props.canMove) {
            // 计算modal应该随鼠标移动到的坐标
            const x = position.mouseX - this.state.position.diffX;
            const y = position.mouseY - this.state.position.diffY;
            // 窗口大小，结构限制，需要做调整，减去侧边栏宽度
            const { clientWidth, clientHeight } = document.documentElement;
            const modal = document.getElementsByClassName("serviceBox")[0];
            if (modal) {
                // 计算modal坐标的最大值
                const maxHeight = clientHeight - modal.offsetHeight;
                const maxWidth = clientWidth - modal.offsetWidth;
                // 判断得出modal的最终位置，不得超出浏览器可见窗口
                const left = x > 0 ? (x < maxWidth ? x : maxWidth) : 0;
                const top = y > 0 ? (y < maxHeight ? y : maxHeight) : 0;
                this.changeState('moveTo',{left, top})
            }
        }
    };
    //点击关闭客服，显示提示弹窗
    closeServiceBox=()=>{
        this.changeState('modalVisible',true);   //显示弹窗
    };
    //点击提示弹窗“确认”
    handleOk = (e) => {
        this.changeState('modalVisible',false);   //关闭弹窗
        this.props.closeServiceBox();   //关闭客服窗口
    };
    //点击提示弹窗“取消”
    handleCancel = (e) => {
        this.changeState('modalVisible',false);   //关闭弹窗
    };
    //显示聊天
    showChatContent=()=>{
        let showData=[];
        if (this.state.chatData.length>5){
            showData=this.state.chatData.slice(this.state.chatData.length-5,this.state.chatData.length);
        }else {
            showData=[...this.state.chatData];
            if (showData[0].time===''){
                showData[0].time=this.getNowTime();
            }
        }
        let chatDom=[];
        showData.forEach((item,index)=>{
            chatDom.push(<div className='chatItem' key={index}>
                    <div>
                        <div>{item.name}</div>
                        <div>{item.time}</div>
                    </div>
                    <div>{item.chat}</div>
                </div>
            )
        });
        return chatDom
    };
    //输入咨询内容
    talkSth=(e)=>{
        this.changeState('ziXun',e.target.value)
    };
    //点击发送
    toChat=(e)=>{
        const thisUser=JSON.parse(sessionStorage.getItem('userdata'));
        const newChat=[...this.state.chatData];
        newChat.push({time:this.getNowTime(),name:thisUser.username,chat:this.state.ziXun});
        this.changeState('chatData',newChat);
        this.changeState('ziXun','');   //清空输入框
    };
    render() {
        const addContent=this.showChatContent();
        return (
            <div className='serviceBox' style={{left:this.state.moveTo.left,top:this.state.moveTo.top}} id='serviceBoxId'>
                {/*头部*/}
                <div className='header' onMouseDown={this.toMove} onMouseMove={this.onMouseMove} onMouseUp={this.onMouseUp} >
                    <div>客服</div>
                    <div onClick={this.closeServiceBox}>×</div>
                </div>
                {/*点击 X 关闭时的提示框*/}
                <Modal
                    title="提示"
                    okText='确认'
                    cancelText='取消'
                    visible={this.state.modalVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={300}
                    getContainer={()=>document.getElementById('serviceBoxId')}
                >
                    您确定退出咨询并关闭当前窗口吗?
                </Modal>
                {/*主体内容部分*/}
                <div className='content'>
                    {addContent}
                </div>
                {/*输入部分*/}
                <div className='textareaBox'>
                    <TextArea
                        placeholder="请输入咨询内容"
                        rows={2}
                        maxLength={50}
                        value={this.state.ziXun}
                        onChange={this.talkSth}
                    />
                    <div>
                        <Button type='primary' onClick={this.toChat}>发送</Button>
                    </div>
                </div>
            </div>
        );
    }
}

export default ServiceBox;